// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.web.action;

import java.util.Date;
import java.util.GregorianCalendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.shared.service.LoginService;
import net.taviscaron.drivenotes.web.forward.ActionRedirect;
import net.taviscaron.drivenotes.web.auth.AuthorizationData;
import net.taviscaron.drivenotes.web.core.Constants;
import net.taviscaron.drivenotes.web.forward.RequestForwarder;
import net.taviscaron.drivenotes.web.forward.ViewForward;
import org.springframework.beans.factory.annotation.Required;

/**
 * Login action
 * @author Andrei Senchuk
 */
public class LoginAction implements Action {
    public enum Error {
        SUCH_USER_NOT_FOUND
    }

    private static final RequestForwarder LOGIN_PAGE_FORWARD = 
            new ViewForward("login");

    private LoginService loginService;

    @Required
    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    public RequestForwarder doAction(HttpServletRequest request, HttpServletResponse response) {
        if(request.getAttribute(Constants.AUTHORIZED_USER_ATTR_NAME) != null) {
            return new ActionRedirect("garage");
        }

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(username == null && password == null) {
            return LOGIN_PAGE_FORWARD;
        }
        
        User user = loginService.findUserByCredentials(username, password);
        if(user != null) {
            HttpSession session = request.getSession();

            AuthorizationData authorizationData = new AuthorizationData();
            authorizationData.setUserId(user.getId());
            Date time = GregorianCalendar.getInstance().getTime();
            authorizationData.setLastAccessTime(time);
            authorizationData.setLoginTime(time);

            session.setAttribute(Constants.AUTHORIZATION_DATA_ATTR_NAME, authorizationData);

            return new ActionRedirect("garage");
        } else {
            request.setAttribute("error", Error.SUCH_USER_NOT_FOUND);
            return LOGIN_PAGE_FORWARD;
        }
    }
}
